import React, { useState, useEffect } from 'react';
import { LineChart, Line, XAxis, YAxis, CartesianGrid, Tooltip, Legend, ResponsiveContainer, AreaChart, Area } from 'recharts';
import { Card, CardContent, Typography, Divider, Box } from '@mui/material';
import { apiRequest } from '../utils/api';

// 模拟车辆数据获取
const fetchVehicleData = async (vehicleId) => {
  try {
    // 实际项目中替换为真实API调用
    const response = await apiRequest.get(`/api/vehicle-data/${vehicleId}`);
    return response.data;
  } catch (error) {
    console.error('Failed to fetch vehicle data:', error);
    // 在开发环境下，尝试从localStorage获取模拟数据
    if (process.env.NODE_ENV === 'development') {
      const mockVehicles = localStorage.getItem('mockVehicles');
      if (mockVehicles) {
        const vehicles = JSON.parse(mockVehicles);
        const vehicle = vehicles.find(v => v.id === vehicleId);
        if (vehicle) {
          console.log('Using mock data from localStorage for vehicle:', vehicleId);
          // 为特定车辆生成更真实的数据
          return Array(24).fill(0).map((_, i) => {
            // 模拟一天中的速度变化模式
            let baseSpeed = 40;
            if (i >= 7 && i <= 9) baseSpeed = 80; // 早高峰
            if (i >= 17 && i <= 19) baseSpeed = 75; // 晚高峰
            if (i >= 0 && i <= 5) baseSpeed = 20; // 凌晨
            
            const speed = baseSpeed + Math.floor(Math.random() * 30);
            
            // 基于速度模拟油耗变化
            const fuelLevel = 100 - (i * 2) - Math.floor(Math.random() * 10);
            
            // 基于车辆状态模拟温度
            let baseTemp = 75;
            if (vehicle.status === 'WARNING') baseTemp = 90;
            const temperature = baseTemp + Math.floor(Math.random() * 15);
            
            return {
              time: `${i}:00`,
              speed: speed,
              fuelLevel: Math.max(10, fuelLevel), // 确保不低于10%
              temperature: temperature,
              location: {
                lat: parseFloat(vehicle.location === '北京市朝阳区' ? '39.9042' : vehicle.location === '上海市浦东新区' ? '31.2304' : vehicle.location === '广州市天河区' ? '23.1291' : vehicle.location === '成都市锦江区' ? '30.6595' : '30.2741'),
                lng: parseFloat(vehicle.location === '北京市朝阳区' ? '116.4074' : vehicle.location === '上海市浦东新区' ? '121.4737' : vehicle.location === '广州市天河区' ? '113.3341' : vehicle.location === '成都市锦江区' ? '104.0657' : '120.1551')
              }
            };
          });
        }
      }
    }
    
    // 如果没有找到本地模拟数据，返回默认模拟数据
    return Array(24).fill(0).map((_, i) => ({
      time: `${i}:00`,
      speed: Math.floor(Math.random() * 120) + 30,
      fuelLevel: Math.floor(Math.random() * 50) + 50,
      temperature: Math.floor(Math.random() * 20) + 70,
      location: {
        lat: 39.9042 + (Math.random() * 0.1 - 0.05),
        lng: 116.4074 + (Math.random() * 0.1 - 0.05)
      }
    }));
  }
};

const VehicleDataChart = ({ vehicleId }) => {
  const [vehicleData, setVehicleData] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);

  useEffect(() => {
    const loadData = async () => {
      try {
        setLoading(true);
        const data = await fetchVehicleData(vehicleId);
        setVehicleData(data);
        setError(null);
      } catch (err) {
        setError('Failed to load vehicle data.');
        console.error(err);
      } finally {
        setLoading(false);
      }
    };

    loadData();
    // 每30秒刷新一次数据
    const interval = setInterval(loadData, 30000);
    return () => clearInterval(interval);
  }, [vehicleId]);

  if (loading) {
    return (
      <Card>
        <CardContent>
          <Typography variant="h6" align="center">Loading vehicle data...</Typography>
        </CardContent>
      </Card>
    );
  }

  if (error) {
    return (
      <Card>
        <CardContent>
          <Typography variant="h6" color="error" align="center">{error}</Typography>
        </CardContent>
      </Card>
    );
  }

  return (
    <Card sx={{ mb: 4 }}>
      <CardContent>
        <Typography variant="h5" gutterBottom>Vehicle Data Visualization</Typography>
        <Typography variant="subtitle1" color="text.secondary" gutterBottom>
          Vehicle ID: {vehicleId}
        </Typography>
        <Divider sx={{ mb: 3 }} />

        <Box sx={{ height: 400, mb: 4 }}>
          <ResponsiveContainer width="100%" height="100%">
            <LineChart data={vehicleData} margin={{ top: 5, right: 30, left: 20, bottom: 5 }}>
              <CartesianGrid strokeDasharray="3 3" />
              <XAxis dataKey="time" />
              <YAxis yAxisId="left" orientation="left" stroke="#8884d8" />
              <YAxis yAxisId="right" orientation="right" stroke="#82ca9d" />
              <Tooltip />
              <Legend />
              <Line yAxisId="left" type="monotone" dataKey="speed" stroke="#8884d8" activeDot={{ r: 8 }} name="Speed (km/h)" />
              <Line yAxisId="right" type="monotone" dataKey="fuelLevel" stroke="#82ca9d" name="Fuel Level (%)" />
            </LineChart>
          </ResponsiveContainer>
        </Box>

        <Box sx={{ height: 300 }}>
          <Typography variant="h6" gutterBottom>Engine Temperature</Typography>
          <ResponsiveContainer width="100%" height="100%">
            <AreaChart data={vehicleData} margin={{ top: 10, right: 30, left: 0, bottom: 0 }}>
              <defs>
                <linearGradient id="tempGradient" x1="0" y1="0" x2="0" y2="1">
                  <stop offset="5%" stopColor="#ff7300" stopOpacity={0.8}/>
                  <stop offset="95%" stopColor="#ff7300" stopOpacity={0.1}/>
                </linearGradient>
              </defs>
              <CartesianGrid strokeDasharray="3 3" />
              <XAxis dataKey="time" />
              <YAxis domain={[60, 100]} />
              <Tooltip />
              <Area type="monotone" dataKey="temperature" stroke="#ff7300" fillOpacity={1} fill="url(#tempGradient)" name="Temperature (°C)" />
            </AreaChart>
          </ResponsiveContainer>
        </Box>
      </CardContent>
    </Card>
  );
};

export default VehicleDataChart;